/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
//19. 删除链表的倒数第 N 个结点
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {   
         //设置指针,快慢指针
        ListNode pre = new ListNode(0);//虚拟头结点

        pre.next = head;
        ListNode start = pre, end = pre;
         while(n != 0) {
            start = start.next;//start先走n步
            n--;
        }

        while(start.next != null) {//start不为空,end和start同时向前走
            start = start.next;
            end = end.next;//end指向n+1的位置
        }
        end.next = end.next.next;
        return pre.next;
    }
}

